package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"monitor_serve/initialize"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

type ExcelDataApi struct{}

// ReceiveExcelDataApi:传入客户名和文件
func (e *ExcelDataApi) ReceiveExcelDataApi(c *gin.Context) {
	//0.接收客户名
	customerName := c.PostForm("customerName")
	if customerName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "客户名不能为空"})
	}
	//0.2.接收文件excel文件
	file, fileheader, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		initialize.Log.Error(customerName, "传入文件失败!")
		return
	}
	//1.先找到到一级文件ExcelData
	baseDir := "ExcelData"
	if _, err := os.Stat(baseDir); os.IsNotExist(err) {
		err = os.MkdirAll(baseDir, 0755)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "创建一级目录失败"})
			return
		}
	}
	//2.根据客户名找到自己的二级文件夹
	customerDir := filepath.Join(baseDir, strings.ReplaceAll(customerName, " ", "_")) //确保没有空格
	if _, err := os.Stat(customerDir); os.IsNotExist(err) {
		err := os.MkdirAll(customerDir, 0755)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "创建客户目录失败"})
			return
		}
	}
	//3.将料仓信息数据和包裹数据导入
	//3.2构建文件保存路径
	fileName := fileheader.Filename
	filePath := filepath.Join(customerDir, fileName)
	//保存文件
	dst, err := os.Create(filePath)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建文件失败"})
		return
	}
	defer dst.Close()
	//写入文件
	_, err = io.Copy(dst, file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "写入文件失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "文件上传成功。"})
	initialize.Log.Info(customerName, "_上传文件成功_", fileName)
	//检查文件是否超过设置容量
	count, err := e.DeleteExcelData(customerName)
	if err != nil {
		initialize.Log.Error("清理excelData失败_", customerName, "_", err)
	}
	fmt.Println("数量", count)
}

// 传入二级目录名，检测该目录下的文件个数，最多保存33个吧
func (e *ExcelDataApi) DeleteExcelData(filePath string) (int, error) {
	//1.0检查是否有该目录，那么目录就会变成ExcelData\filePath
	filePath2 := "ExcelData" + "/" + filePath
	if _, err := os.Stat(filePath2); os.IsNotExist(err) {
		return 0, fmt.Errorf("directory does not exist: %s", filePath)
	}
	//2.0进行检测
	//2.1读取文件信息
	files, err := os.ReadDir(filePath2)
	if err != nil {
		return 0, fmt.Errorf("error reading directory: %s", err)
	}
	//2.2将文件信息按时间排序
	var fileInfos []os.FileInfo
	for _, file := range files {
		if !file.IsDir() {
			fileInfo, err := file.Info()
			if err != nil {
				return 0, fmt.Errorf("error getting file info: %s", err)
			}
			fileInfos = append(fileInfos, fileInfo)
		}
	}
	if len(fileInfos) > 33 {
		//按时间排序
		sort.Slice(fileInfos, func(i, j int) bool {
			return fileInfos[i].ModTime().After(fileInfos[j].ModTime())
		})
		//只保留最新的50个文件
		for _, file := range fileInfos[33:] {
			if err := os.Remove(filepath.Join(filePath2, file.Name())); err != nil {
				return 0, fmt.Errorf("error deleting file: %s", err)
			}
		}
	}
	fileCount := len(fileInfos)
	return fileCount, nil
}
